package com.mryang.hds.service.impl;

import com.mryang.hds.configs.AppException;
import com.mryang.hds.entity.User;
import com.mryang.hds.mapper.LoginMapper;
import com.mryang.hds.service.ILoginService;
import com.mryang.hds.utils.ResultCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author Genius
 * @version 1.0.0
 * @ClassName LoginServiceImpl.java
 * @Description TODO
 * @createTime 2022年12月27日 14:05:00
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class LoginServiceImpl implements ILoginService {

    @Resource
    private LoginMapper loginMapper;


    @Override
    public User getLoginUser(String idcard, String password) {

        try {
            // 查找用户信息
            return loginMapper.getLoginUser(idcard, password);

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.USER_CREDIT_NOT_ENOUTH);
        }

    }

    /**
     * 添加用户
     * @param user 待添加用户信息
     * @return 是否添加成功
     */
    @Transactional
    @Override
    public int insertUser(User user) {

        try {
            // 该身份信息的用户已存在
            // if(loginMapper.getUserByIdCard(user.getIdCard()) != null || loginMapper.getUserByPhone(user.getPhone()) != null){
            if(loginMapper.getUserByIdCard(user.getIdCard()) != null){
                return 0;
            }
            // 先将 部分信息添加到 user表
            int i = loginMapper.insertUser(user);

            // 将 身份证号及正反面照片 添加到 注册表
            // i += loginMapper.insertReg(user.getIdCard(), user.getIdCardFrontImage(), user.getIdCardBackImage());

            return i;

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.USER_ADDITION_FAILED);
        }
    }


    @Override
    public User getLoginUserByPhone(String phone, String password) {
        try {
            User loginUserByPhone = loginMapper.getLoginUserByPhone(phone, password);
            return loginUserByPhone;
        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.USER_CREDIT_NOT_ENOUTH);
        }

    }
}
